package edu.upc.dew.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleCipher {

   private static final Logger log = LoggerFactory.getLogger(SimpleCipher.class);    
    
    private static final byte[] linebreak = {}; // Remove Base64 encoder default linebreak
    private static final String secret = "K!@LMSCALMSCPTV$"; // secret key length must be 16
    private static SecretKey key;
    private static Cipher cipher;
    private static org.apache.commons.codec.binary.Base64 coder;

    static {
        try {
            key = new SecretKeySpec(secret.getBytes(), "AES");
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
            coder = new org.apache.commons.codec.binary.Base64(32, linebreak, true);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }

    public static synchronized String encrypt(String plainText) throws Exception {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherText = cipher.doFinal(plainText.getBytes());
        return new String(coder.encode(cipherText));
    }

    public static synchronized String decrypt(String codedText) throws Exception {
        byte[] encypted = coder.decode(codedText.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(encypted);
        return new String(decrypted);
    }
}
